package leecode.q257;

import java.util.ArrayList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    TreeNode root = new TreeNode(1);

    {
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(5);
    }

    List<String> res = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        findAllPaths(root, new ArrayList<>());
        return res;
    }

    private void findAllPaths(TreeNode node, List<Integer> sub) {
        sub.add(node.val);
        if (node.left == null && node.right == null) { // 这是个叶子节点，存储
            res.add(str(sub));
            return;
        }
        if (node.left != null) {
            findAllPaths(node.left, sub);
            sub.remove(sub.size() - 1);
        }
        if (node.right != null) {
            findAllPaths(node.right, sub);
            sub.remove(sub.size() - 1);
        }
    }

    private String str(List<Integer> sub) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < sub.size(); i++) {
            Integer integer = sub.get(i);
            stringBuilder.append(integer);
            if (i != sub.size() - 1) {
                stringBuilder.append("->");
            }
        }
        return stringBuilder.toString();
    }
}
